from flask import current_app, jsonify
from flask import render_template
from flask import request

from cyds.models import Squad
from . import works_blu


@works_blu.route('/list')
def works_show():
    """返回作品列表"""
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '16')
    school = request.args.get('category', '7')

    try:
        page = int(page)
        per_page = int(per_page)
        school = int(school)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=403, errmsg="参数错误")

    try:
        paginate = Squad.query.filter_by(school=school).order_by(Squad.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=404, errmsg="数据查询错误")

    squad_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转成字典列表
    squad_dict_li = []
    for squad_list in squad_model_list:
        squad_dict = {
            "id": squad_list.id,
            "name": squad_list.name,
            "school": squad_list.school,
            "video_url": squad_list.video_url,
            "profession": squad_list.profession,
            "grade": squad_list.grade
        }
        squad_dict_li.append(squad_dict)

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "squad_dict_li": squad_dict_li
    }

    return render_template("front/squad_list.html", data=data)
